
package com.scs.application.modules.base.controller;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.exceptions.ExportException;
import com.scs.application.core.exceptions.ImportException;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.model.ImportResult;
import com.scs.application.core.model.PageResult;
import com.scs.application.core.model.RestResult;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.mvc.controller.ImAndExAbleController;
import com.scs.application.core.utils.PoiUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.base.dto.ExcelHospitalMaterialDTO;
import com.scs.application.modules.base.entity.Hospital;
import com.scs.application.modules.base.entity.HospitalMaterial;
import com.scs.application.modules.base.entity.Material;
import com.scs.application.modules.base.request.HospitalMaterialQueryRequest;
import com.scs.application.modules.base.service.HospitalMaterialService;
import com.scs.application.modules.base.service.HospitalService;
import com.scs.application.modules.base.service.MaterialService;
import com.scs.application.modules.design.service.QueryGenerator;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * HospitalMaterial controller
 */
@AllArgsConstructor
@RestController
@SuppressWarnings("/all")
@RequestMapping("/base/hospital_materials")
public class HospitalMaterialController extends CrudController<HospitalMaterial, String, HospitalMaterialService> implements ImAndExAbleController<HospitalMaterialQueryRequest> {
    private final MaterialService materialService;
    private final HospitalService hospitalService;

    @GetMapping("/page")
    public PageResult page(HospitalMaterialQueryRequest request) {
        IPage page = service.page(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }


    @GetMapping("/list")
    public CommonResult list(HospitalMaterialQueryRequest request) {
        List<HospitalMaterial> list = service.list(request);
        return CommonResult.ok("查询成功", list);
    }

    @Override
    public CommonResult update(@RequestBody @Valid HospitalMaterial entity) {
        //判断单位单价订单单位订单数量是否为空
        if (StringUtils.isBlank(entity.getUnit()) || entity.getPrice() == null || StringUtils.isBlank(entity.getOrderUnit()) || entity.getOrderQty() == null) {
            throw new BusinessException("单位、单价、订单单位、订单数量均不能为空！");
        }
        return super.update(entity);
    }

    /**
     * TODO 修改URL 为 /{id}/active，同时前端也需要修改
     * 医院商品启用
     *
     * @param id
     * @return
     */
    @PostMapping("/active/{id}")
    public CommonResult active(@PathVariable("id") String id) {
        service.active(id);
        return CommonResult.ok("启用成功");
    }

    /**
     * TODO 修改URL 为 /{id}/deactive，同时前端也需要修改
     * 医院商品停用
     *
     * @param id
     * @return
     */
    @PostMapping("/deactive/{id}")
    public CommonResult deactive(@PathVariable("id") String id) {
        service.deactive(id);
        return CommonResult.ok("停用成功");
    }

    /**
     * 采购订单-订单明细，关键字搜索医院商品
     *
     * @param request
     * @return
     */
    @GetMapping("/page_by_keywords")
    public CommonResult pageByKeywords(HospitalMaterialQueryRequest request) {
        IPage page = service.pageByKeyword(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    /**
     * 全部启用
     *
     * @return
     */
    @PostMapping("/all_active")
    public CommonResult allActive() {
        service.allActive();
        return CommonResult.ok("全部启用成功");
    }

    /**
     * 全部停用
     *
     * @return
     */
    @PostMapping("/all_inactive")
    public CommonResult allInactive() {
        service.allInactive();
        return CommonResult.ok("全部停用成功");
    }


    /**
     * 医院供应商耗材导出数据模板
     */
    @Override
    public void excelTemplate(HospitalMaterialQueryRequest request) {
        String fileName = "6医院供应商供货关系导入.xlsx";
        ExportParams params = PoiUtils.getDefaultExportParams("医院供应商耗材导入模板", "医院供应商耗材信息", true);
        params.setExclusions(new String[]{"错误行号", "错误信息"});
        if (UserUtils.isSupplier()) {
            params.setExclusions(new String[]{"错误行号", "错误信息", "品类名称"});
        }
        ExcelHospitalMaterialDTO mockData = PoiUtils.mockData(ExcelHospitalMaterialDTO.class);
        try {
            setDownloadParam(fileName);
            PoiUtils.exportExcel(response().getOutputStream(), params, ExcelHospitalMaterialDTO.class, Lists.newArrayList(mockData));
        } catch (IOException e) {
            throw new ExportException("导出异常", e);
        }
    }

    /**
     * 医院供应商耗材导入数据
     */
    /**
     * 商品管理 导入数据
     */
    @Override
    public CommonResult<ImportResult> excelImport(MultipartFile file) throws ImportException {
        return CommonResult.ok("导入成功", service.excelImport(file));
    }

    private void fillData(HospitalMaterial entity) {
        Material material = materialService.getById(entity.getMaterialId());
        if (material != null) {
            entity.setMaterialTypeCode(material.getMaterialTypeCode());
        }
        Hospital hospital = hospitalService.getById(entity.getHospitalId());
        if (hospital != null) {
            entity.setFlagEnabledMaterialEdit(hospital.getFlagEnabledMaterialEdit() != null ? hospital.getFlagEnabledMaterialEdit() : false);
            entity.setEnabledMaterialEditRemark(hospital.getEnabledMaterialEditRemark());
        } else{
            entity.setFlagEnabledMaterialEdit(false);
        }
    }

    /***
     * @param id
     * @Description:  通用查找，单个
     */
    @Override
    @GetMapping("/findByIdCommon")
    public RestResult findByIdCommon(@RequestParam("id") Serializable id) {
        HospitalMaterial entity = service.getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        fillData(entity);
        return RestResult.ok("获取数据成功", entity);
    }

    /***
     * @param request
     * @Description:  通用分页
     */
    @GetMapping("/pageCommon")
    public PageResult pageCommon(HttpServletRequest request, HospitalMaterial entity) {
        IPage<HospitalMaterial> page = QueryGenerator.parsePage(request);
        QueryWrapper<HospitalMaterial> queryWrapper = QueryGenerator.initQueryWrapper(request);
        fillQueryAuth(queryWrapper,entity);
        IPage<HospitalMaterial> pageResult = service.page(page, queryWrapper);
        if (pageResult.getTotal() > 0) {
            List<String> HospitalIdList = pageResult.getRecords().stream().map(HospitalMaterial::getHospitalId).distinct().collect(Collectors.toList());
            Map<String,Hospital> HospitalById =  hospitalService.list(Wrappers.<Hospital>query().in("id",HospitalIdList)).stream().collect(Collectors.toMap(Hospital::getId, t -> t));
            Hospital hospital;
            for (HospitalMaterial hospitalMaterial : pageResult.getRecords()) {
                hospital = HospitalById.get(hospitalMaterial.getHospitalId());
                if (hospital != null) {
                    hospitalMaterial.setFlagEnabledMaterialEdit(hospital.getFlagEnabledMaterialEdit() != null ? hospital.getFlagEnabledMaterialEdit() : false);
                    hospitalMaterial.setEnabledMaterialEditRemark(hospital.getEnabledMaterialEditRemark());
                }else{
                    hospitalMaterial.setFlagEnabledMaterialEdit(false);
                }
            }
        }
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }

}
